package com.blue.base.oauth.server.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blue.base.oauth.common.dto.AuthUserDetailDto;
import com.blue.base.oauth.server.entity.User;
import com.blue.base.oauth.server.mappers.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author liulei
 * @version 1.0
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public AuthUserDetailDto loadUserByUsername(String account) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
        if (null == user) {
            throw new RuntimeException("用户名或密码错误");
        }
        AuthUserDetailDto userDetailDto = new AuthUserDetailDto();
        BeanUtils.copyProperties(user, userDetailDto);
        List<String> roles = Arrays.asList("ROLE_ADMIN");
        userDetailDto.setRoles(roles);
        return userDetailDto;
    }
}
